﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Bll;
using Commons;
using DAL;
using SimpComm;
using ViewModel;
using log4net;

namespace UI4._0.Areas.adm.Controllers
{
    public class AdmColController : Controller
    {
        //
        // GET: /adm/AdmMain/

        private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private readonly AdmColService bs = AdmColService.Instance;

        [AdminAuthorize("查看管理后台栏目", ClassLevel: 2, AdmColID: 1, Url: "/adm/AdmCol/Index")]
        public ActionResult Index(int page = 1, int pageSize = 5, int ClassLevel = 0, int AdmColID = 0)
        {
            ViewBag.Title = "查看管理后台栏目";
            var select = DynamicLinqExpressions.True<AdmCol>();
            if (ClassLevel != 0)
                select = select.And(p => p.ClassLevel == ClassLevel);
            if (AdmColID != 0)
                select = select.And(p => p.AdmColID == AdmColID);

            var bigclass = bs.SM_List(new SMP<AdmCol, AdmColListModel>()
                                          {
                                              page = page,
                                              pageSize = pageSize,
                                              selected = select.Compile(),
                                          });
            bigclass.MyRoutes.Add("ClassLevel", ClassLevel.ToString());
            bigclass.MyRoutes.Add("AdmColID", AdmColID.ToString());
            return View(bigclass);
        }

        public ActionResult MainContent()
        {
            ViewBag.Title = "管理面板";
            return View();
        }

        [AdminAuthorize("管理面板")]
        public ActionResult Main()
        {
            var bigclass = bs.SM(new SMP<AdmCol, AdmColListModel>()
                                                  {

                                                      pageSize = 8,
                                                      selected = p => p.ClassLevel == 1,
                                                      getmodel = p => new AdmColListModel()
                                                                   {
                                                                       ID = p.ID,
                                                                       Name = p.Name
                                                                   },
                                                  });
            var result = new TheSecondClassView()
                             {
                                 Name = "根目录"
                             };
            using (var db = new PizzaDataDataContext())
            {
                var SecondClasss = bigclass.Datas.GroupJoin(db.AdmCol.Where(p => p.ClassLevel == 2).Select(p => p),
                                                            p => p.ID,
                                                            p => p.AdmColID, (p, c) => new
                                                                                           {
                                                                                               p.Name,
                                                                                               c
                                                                                           });
                foreach (var x in SecondClasss)
                {
                    var r1 = new TheSecondClassView()
                                 {
                                     Name = x.Name,
                                 };
                    var select1 = from p in x.c
                                  group p by p.SmallClass
                                      into g
                                      select new { key = g.Key, data = g };
                    foreach (var y in select1)
                    {

                        var r2 = new TheSecondClassView()
                        {
                            Name = y.key,//小分类
                        };
                        foreach (var admCol in y.data.OrderBy(p => p.OrderBy))
                        {
                            r2.TheSecondClasses.Add(new TheSecondClassView()
                            {
                                Name = admCol.Name,
                                Url = admCol.Url,
                            });
                        }
                        r1.TheSecondClasses.Add(r2);
                    }
                    result.TheSecondClasses.Add(r1);
                }
            }
            var data = new MS<MD<AdmColListModel>, TheSecondClassView, string>()
            {
                D1 = bigclass,
                D2 = result,
                D3 = "/adm/AdmCol/Index"
                //                D3 = "/adm/AdmCol/MainContent"
            };

            return View(data);
        }


        [HttpPost]
        [AdminAuthorize("删除后台栏目")]
        public string Delete(int ID)
        {
            var msg = bs.Delete(ID);
            return msg.ToJsonStr();
        }


        [HttpPost]
        [AdminAuthorize("删除后台栏目")]
        public string MulDelete(string IDs)
        {
            List<int> id_ls = IDs.TransIntLs();
            if (id_ls.Count == 0)
                return new MsgBox(false, "请输入要批量删除的数据").ToJsonStr();
            var msg = bs.Delete(p => id_ls.Contains(p.ID));
            return msg.ToJsonStr();
        }

        [AdminAuthorize("增改后台栏目")]
        public ActionResult Opear(int ID = 0, MsgBox msg = null)
        {
            if (msg != null && msg.Success == false)
            {
                ViewData["DebugMess"] = msg.Message;
            }
            if (ID > 0)
            {
                var admCol = bs.GetModel(p => p.ID == ID, p => new AdmColUpdateModel()
                                                                {
                                                                    AdmColID = p.AdmColID,
                                                                    ClassLevel = p.ClassLevel,
                                                                    Descript = p.Descript,
                                                                    ID = p.ID,
                                                                    IsOpenWin = p.IsOpenWin,
                                                                    Name = p.Name,
                                                                    OrderBy = p.OrderBy,
                                                                    SmallClass = p.SmallClass,
                                                                    Url = p.Url
                                                                });
                return View(admCol);
            }
            else
            {
                return View(new DataInfo<AdmColUpdateModel>(true, "插入值", new AdmColUpdateModel()));
            }
        }

        [HttpPost]
        [AdminAuthorize("修改添加后台栏目")]
        public string Opear(FormCollection collection)
        {
            var msg = bs.UpdateOrInsertByID(p => new AdmCol()
                {
                    AdmColID = collection["data.AdmColID"].ObjToInt(),
                    ClassLevel = collection["data.ClassLevel"].ObjToByteNull(),
                    Descript = collection["data.Descript"],
                    IsOpenWin = collection["data.IsOpenWin"].ObjToBoolByString(),
                    Name = collection["data.Name"],
                    OrderBy = collection["data.OrderBy"].ObjToShort(),
                    SmallClass = collection["data.SmallClass"],
                    Url = collection["data.Url"],
                }, p => p.ID == collection["data.ID"].ObjToInt());
            return msg.ToJsonStr();
        }
        [AdminAuthorize("查看后台栏目")]
        public ActionResult Details(int ID)
        {
            var data = bs.GetAEntity(p => p.ID == ID);
            return View(data);
        }


        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(AdmLogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var msg = AdmInfo.Instance.Login(model.UserName, model.Password);
                if (msg.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") &&
                        !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                        return Redirect(returnUrl);
                    else
                        return RedirectToAction("Main", "AdmCol");
                }
                else
                {
                    if (logger.IsDebugEnabled)
                        logger.Info("LogOn Error:" + msg.Message + "|Ip:" + this.GetIP());
                    ModelState.AddModelError("", msg.Message + "账号sa,密码sa");
                }
            }
            return View();
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "AdmCol");
        }
    }
}
